import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Image,
  SafeAreaView
} from 'react-native';

interface Message {
  id: string;
  text: string;
  isUser: boolean;
  timestamp: number;
}

interface ChatScreenProps {
  route?: {
    params?: {
      character?: {
        id: string;
        name: string;
        avatar: string;
      }
    }
  };
  navigation?: any;
}

const ChatScreen: React.FC<ChatScreenProps> = ({ route, navigation }) => {
  const character = route?.params?.character || { 
    id: '1', 
    name: '小M', 
    avatar: 'https://via.placeholder.com/40' 
  };
  
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      text: `你好！我是${character.name}，有什么我可以帮助你的吗？`,
      isUser: false,
      timestamp: Date.now() - 60000
    }
  ]);
  
  const [isTyping, setIsTyping] = useState(false);
  const flatListRef = useRef<FlatList>(null);

  useEffect(() => {
    if (navigation) {
      navigation.setOptions({
        title: character.name,
      });
    }
  }, [navigation, character]);

  const handleSend = () => {
    if (!message.trim()) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      text: message.trim(),
      isUser: true,
      timestamp: Date.now()
    };

    setMessages(prev => [...prev, userMessage]);
    setMessage('');
    setIsTyping(true);

    // 滚动到底部
    setTimeout(() => {
      flatListRef.current?.scrollToEnd({ animated: true });
    }, 100);

    // 模拟AI回复
    setTimeout(() => {
      const aiMessage: Message = {
        id: (Date.now() + 1).toString(),
        text: getAIResponse(message.trim()),
        isUser: false,
        timestamp: Date.now()
      };

      setMessages(prev => [...prev, aiMessage]);
      setIsTyping(false);

      // 滚动到底部
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);
    }, 1000 + Math.random() * 1000);
  };

  const getAIResponse = (userMessage: string): string => {
    // 简单模拟AI回复逻辑
    if (userMessage.includes('你好') || userMessage.includes('hi') || userMessage.includes('hello')) {
      return `你好！有什么我可以帮助你的吗？`;
    }

    if (userMessage.includes('天气')) {
      return '今天天气晴朗，温度适宜，是个出行的好日子！';
    }

    if (userMessage.includes('名字') || userMessage.includes('介绍')) {
      return `我是${character.name}，很高兴认识你！`;
    }

    // 默认回复
    return `关于"${userMessage}"，我需要进一步了解，能告诉我更多详情吗？`;
  };

  const formatTime = (timestamp: number): string => {
    const date = new Date(timestamp);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };

  const renderMessage = ({ item, index }: { item: Message, index: number }) => {
    const showTimestamp = index === 0 || 
      (item.timestamp - messages[index - 1].timestamp > 5 * 60 * 1000);
    
    return (
      <View style={styles.messageContainer}>
        {showTimestamp && (
          <Text style={styles.timestamp}>{formatTime(item.timestamp)}</Text>
        )}
        
        <View style={[
          styles.messageBubble,
          item.isUser ? styles.userBubble : styles.aiBubble
        ]}>
          {!item.isUser && (
            <Image 
              source={{ uri: character.avatar }} 
              style={styles.avatar} 
            />
          )}
          
          <View style={[
            styles.messageContent,
            item.isUser ? styles.userMessageContent : styles.aiMessageContent
          ]}>
            <Text style={styles.messageText}>{item.text}</Text>
          </View>
          
          {item.isUser && (
            <Image 
              source={{ uri: 'https://via.placeholder.com/40' }} 
              style={styles.avatar} 
            />
          )}
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
      >
        <FlatList
          ref={flatListRef}
          data={messages}
          renderItem={renderMessage}
          keyExtractor={item => item.id}
          contentContainerStyle={styles.messagesList}
          onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
        />
        
        {isTyping && (
          <View style={styles.typingContainer}>
            <View style={styles.typingBubble}>
              <Text style={styles.typingText}>{character.name}正在输入...</Text>
            </View>
          </View>
        )}
        
        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            value={message}
            onChangeText={setMessage}
            placeholder="输入消息..."
            multiline
          />
          <TouchableOpacity 
            style={[
              styles.sendButton,
              !message.trim() && styles.sendButtonDisabled
            ]}
            onPress={handleSend}
            disabled={!message.trim()}
          >
            <Text style={styles.sendButtonText}>发送</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  messagesList: {
    paddingHorizontal: 16,
    paddingBottom: 16,
  },
  messageContainer: {
    marginBottom: 16,
  },
  timestamp: {
    alignSelf: 'center',
    fontSize: 12,
    color: '#999',
    marginBottom: 8,
  },
  messageBubble: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    marginBottom: 4,
  },
  userBubble: {
    justifyContent: 'flex-end',
  },
  aiBubble: {
    justifyContent: 'flex-start',
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
  },
  messageContent: {
    maxWidth: '70%',
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 10,
    marginHorizontal: 8,
  },
  userMessageContent: {
    backgroundColor: '#3498db',
    borderBottomRightRadius: 4,
  },
  aiMessageContent: {
    backgroundColor: '#fff',
    borderBottomLeftRadius: 4,
  },
  messageText: {
    fontSize: 16,
    color: '#333',
  },
  typingContainer: {
    paddingHorizontal: 16,
    marginBottom: 8,
  },
  typingBubble: {
    alignSelf: 'flex-start',
    backgroundColor: '#f0f0f0',
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  typingText: {
    fontSize: 14,
    color: '#666',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 8,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  input: {
    flex: 1,
    minHeight: 40,
    maxHeight: 120,
    backgroundColor: '#f5f5f5',
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 8,
    marginRight: 12,
    fontSize: 16,
  },
  sendButton: {
    backgroundColor: '#3498db',
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 20,
  },
  sendButtonDisabled: {
    backgroundColor: '#b3d7f0',
  },
  sendButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
});

export default ChatScreen;